package com.itboye.textileexpres.alipaytest;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.itboye.textileexpes.beans.PayWayBean;
import com.itboye.textileexpes.presenter.PayWayPresenter;
import com.itboye.textileexpres.R;
import com.itboye.textileexpres.base.BaseActivity;
import com.itboye.textileexpres.base.ResultEntity;

public class ActivityPaymentMethod extends BaseActivity implements
		OnClickListener, Observer {
	ImageView back;
	private TextView tvmoney;
	TextView topay;
	String price;
	String oedernum;
	PayWayPresenter payWayPresenter;
	PayWayBean model;
	List<PayWayBean> payList = new ArrayList<PayWayBean>();

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_payment_method;
	}

	@Override
	public void onMyCreate() {
		// TODO Auto-generated method stub
		payWayPresenter = new PayWayPresenter(this);
		model = new PayWayBean();
		payWayPresenter.getInfo(model);
		price = getIntent().getStringExtra("price");
		oedernum = getIntent().getStringExtra("orderNum");
		tvmoney.setText(price + "");
		Intent intent = new Intent("updateorder");
		sendBroadcast(intent);
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventTag() == PayWayPresenter.getSuccessEvent) {
				payList.addAll((List<PayWayBean>) entity.getData());
				for (int i = 0; i < payList.size(); i++) {

				}
			}

		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back:
			finish();
			break;
		case R.id.topay:
			// Intent intent = new Intent(ActivityPaymentMethod.this,
			// AlipayTest.class);
			// startActivity(intent);
			pay(oedernum, price);
			break;
		default:
			break;
		}
	}

	/** 支付宝支付业务：入参app_id */
	public static final String APPID = "2016111102714102";
	// public static final String APPID = "";

	/** 支付宝账户登录授权业务：入参pid值 */
	public static final String PID = "";
	/** 支付宝账户登录授权业务：入参target_id值 */
	public static final String TARGET_ID = "";

	/** 商户私钥，pkcs8格式 */
	// public static final String RSA_PRIVATE="";
	public static final String RSA_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMiMe7ITMXL87Pz5ug7AyZhU5KkC1S+UrO7Fu4sG6vvhRXLZrJNaB2gqfQCnvsfon0sgIuLg9Tq8oHyXBUegzYOQVa2yNVZxlJYoAxw0Yvyx8r0XvBP/WHd2UDtXuspT3uCwpoBbSputRbMSKiUcL29R9AdjQohjFan8YBoaPk+vAgMBAAECgYEAu6/uG8wmnSzkRiUY4bG/eZcJoLsL9Um5RoU7bXN9+1jqfAAHqKe7AtuwvSpAPCsS2WYsABT0rJHXyII16MEvU2ZmXMgwhExBo6T35RXtmqx7gCR8/ZXmeDrU20WNmDROQOL2KHKCr46+r7TyxxW1KAUXZecUEF2I+xVgqTdbIlECQQDyr3mw9tfkV0nx6hMrbU7BiR1ZZh7fxuT5MTblnTHR5LPgJ7RebrnzVRuZv8yDgVIhdSsoNpeQ9742nfltwJVrAkEA040yXcxjGeQE4r9hYTvudVl8NzCGpUpwzNqsjP3gFwhRyjJeD9yqiJH+RjXJ4anTDVqggChd+BXJp1+lnIU7zQJAceXVMS7IqEwnUjhPguQsQDy/34NEHjZUpHdqkl0yUpYJrbw0tNU2xHM/HuubamS5TSaWeKsWe10qkquVsuLdvQJAJEuZVJZ4ejywyeZj4rbRlrifoyhkMX+wErWB3T7Bb7IxtismEDqf14aUxZ784Aau+x+NYe+LD8FNM7YpR81kEQJAYGtxV6BJ1yq/ckUyUybl7G8xONJBL3Q6Xp9N9s59xPnBGEIEaRSV8eVjHZ58/tgORtRWKsAY7DHqE790h5B72w==";

	private static final int SDK_PAY_FLAG = 1;
	private static final int SDK_AUTH_FLAG = 2;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@SuppressWarnings("unused")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				@SuppressWarnings("unchecked")
				PayResult payResult = new PayResult(
						(Map<String, String>) msg.obj);
				/**
				 * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
				 */
				String resultInfo = payResult.getResult();// 同步返回需要验证的信息
				String resultStatus = payResult.getResultStatus();
				// 判断resultStatus 为9000则代表支付成功
				if (TextUtils.equals(resultStatus, "9000")) {
					// 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
					Toast.makeText(ActivityPaymentMethod.this, "支付成功",
							Toast.LENGTH_SHORT).show();
				} else {
					// 该笔订单真实的支付结果，需要依赖服务端的异步通知。
					Toast.makeText(ActivityPaymentMethod.this, "支付失败",
							Toast.LENGTH_SHORT).show();
				}
				break;
			}
			case SDK_AUTH_FLAG: {
				@SuppressWarnings("unchecked")
				AuthResult authResult = new AuthResult(
						(Map<String, String>) msg.obj, true);
				String resultStatus = authResult.getResultStatus();

				// 判断resultStatus 为“9000”且result_code
				// 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
				if (TextUtils.equals(resultStatus, "9000")
						&& TextUtils.equals(authResult.getResultCode(), "200")) {
					// 获取alipay_open_id，调支付时作为参数extern_token 的value
					// 传入，则支付账户为该授权账户
					Toast.makeText(
							ActivityPaymentMethod.this,
							"授权成功\n"
									+ String.format("authCode:%s",
											authResult.getAuthCode()),
							Toast.LENGTH_SHORT).show();
				} else {
					// 其他状态值则为授权失败
					Toast.makeText(
							ActivityPaymentMethod.this,
							"授权失败"
									+ String.format("authCode:%s",
											authResult.getAuthCode()),
							Toast.LENGTH_SHORT).show();

				}
				break;
			}
			default:
				break;
			}
		};
	};

	/**
	 * 支付宝支付业务
	 * 
	 * @param v
	 */
	public void pay(String name, String price) {
		/**
		 * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
		 * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
		 * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
		 * 
		 * orderInfo的获取必须来自服务端；
		 */
		if (TextUtils.isEmpty(APPID) || TextUtils.isEmpty(RSA_PRIVATE)) {
			new AlertDialog.Builder(this)
					.setTitle("警告")
					.setMessage("需要配置APPID | RSA_PRIVATE")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(
										DialogInterface dialoginterface, int i) {
									//
									finish();
								}
							}).show();
			return;
		}

		Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID,
				name, price);
		String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
		String sign = OrderInfoUtil2_0.getSign(params, RSA_PRIVATE);
		final String orderInfo = orderParam + "&" + sign;

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				PayTask alipay = new PayTask(ActivityPaymentMethod.this);
				Map<String, String> result = alipay.payV2(orderInfo, true);
				Log.i("msp", result.toString());

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(this);
		String version = payTask.getVersion();
		Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 原生的H5（手机网页版支付切natvie支付） 【对应页面网页支付按钮】
	 * 
	 * @param v
	 */
}
